package com.itttq.gen.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itttq.gen.common.constant.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class GenUtil {
    public final static String NUMBER_LETTER = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    public final static String NUMBER = "0123456789";
    public final static Pattern WRAP_SYMBOL = Pattern.compile("\\s*|\t|\r|\n");
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取时间字符串：20200111120515
     *
     * @return
     */
    public static String getLast24HTimeStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(calendar.getTime());
    }

    /**
     * 获取时间字符串：20200111120515
     *
     * @return
     */
    public static String getTimeStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(Calendar.getInstance().getTime());
    }

    private static String fillZero(int i) {
        return i > 9 ? String.valueOf(i) : "0" + i;
    }

    /**
     * 获取随机数
     *
     * @param len
     * @return
     */
    public static int getRandomNumber(int len) {
        return new SecureRandom().nextInt(len);
    }

    /**
     * 获取随机数，含字母和数字
     *
     * @param len
     * @return
     */
    public static String getRandomNumberAndLetter(int len) {
        return getRandomStr(NUMBER_LETTER, len);
    }

    /**
     * 获取随机数，只含数字
     *
     * @param len
     * @return
     */
    public static String getRandomNumberStr(int len) {
        return getRandomStr(NUMBER, len);
    }

    public static String getRandomStr(String str, int len) {
        SecureRandom random = new SecureRandom();
        //指定字符串长度，拼接字符并toString
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            sb.append(str.charAt(random.nextInt(str.length())));
        }
        return sb.toString();
    }

    /**
     * 简化的UUID，去掉了横线
     *
     * @return 简化的UUID，去掉了横线
     */
    public static String UUID() {
        return UUID.randomUUID().toString().replaceAll(Constants.HORIZONTAL_LINE, "");
    }

    /**
     * 获取本机的Mac地址
     *
     * @return
     */
    public static String getMac() {
        InetAddress ia;
        byte[] mac = null;
        try {
            // 获取本地IP对象
            ia = InetAddress.getLocalHost();
            // 获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
            mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 下面代码是把mac地址拼装成String
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mac.length; i++) {
            if (i != 0) {
                sb.append("-");
            }
            // mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length() == 1 ? 0 + s : s);
        }
        // 把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }

    public static String getIpAddress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");

        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if (index != -1) {
                return XFor.substring(0, index);
            } else {
                return XFor;
            }
        }
        XFor = Xip;
        if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
            return XFor;
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }


    /**
     * 快速压缩文件夹或文件
     *
     * @param dirFile
     * @param zipFilePath
     * @throws Exception
     */
    public static void zipDir(File dirFile, String zipFilePath) throws IOException {
        ZipOutputStream zipOut = null;
        WritableByteChannel writableByteChannel = null;
        FileChannel fileChannel = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(new File(zipFilePath)));
            writableByteChannel = Channels.newChannel(zipOut);
            for (File f : dirFile.listFiles()) {
                fileChannel = new FileInputStream(f).getChannel();
                zipOut.putNextEntry(new ZipEntry(f.getName()));
                fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
            }
        } finally {
            if (null != fileChannel) {
                fileChannel.close();
            }
            if (null != writableByteChannel) {
                writableByteChannel.close();
            }
            if (null != zipOut) {
                zipOut.close();
            }
        }
    }

    /**
     * 写入内容到文本文件
     *
     * @param text
     * @param path
     * @throws IOException
     */
    public static void generateTxt(String text, String path) throws IOException {
        FileWriter fw = null;
        try {
            fw = new FileWriter(new File(path), true);
            fw.write(text);
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除文件和文件夹
     *
     * @param path
     * @throws IOException
     */
    public static void delFile(String path) throws IOException {
        delFile(new File(path));
    }

    public static void delFile(File file) throws IOException {
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                delFile(f);
            }
        }
        file.delete();
    }

    /**
     * 检查redis是否存活
     *
     * @param url      服务器地址
     * @param port     端口
     * @param password 密码
     * @return
     */
    public static boolean getRedisIsOk(String url, int port, String password) {
        boolean result = false;
        try {
            //连接本地Redis服务
            Jedis jedis = new Jedis(url, port);
            if (StringUtils.isNotEmpty(password)) {
                jedis.auth(password);
            }
            String ping = jedis.ping();
            if (ping.equalsIgnoreCase("PONG")) {
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 去掉换行符，包括去掉/t /n /r
     * @param str
     * @return
     */
    public static String replaceWrapSymbol(String str) {
        return null == str ? null : WRAP_SYMBOL.matcher(str).replaceAll("");
    }

}
